
/*
这段代码用于定义并初始化两个自定义内核对象
mykobject01 和mykobject02，
并将它们添加到一个自定义内核对象集合 mykset 中。
测试引用计数
*/

#include <linux/module.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/configfs.h>
#include <linux/kernel.h>
#include <linux/kobject.h>

// 定义三个kobject指针变量
struct kobject *mykobject1;
struct kobject *mykobject2;
struct kobject *mykobject3;

// 定义kobject_type变量
struct kobj_type mytype;

// 模块初始化函数
static int myref_init(void)
{

    // 创建kobject第一种方法
    // 添加mykobject1,打印引用计数
    mykobject1 = kobject_create_and_add("mykobject1", NULL);
   printk("mykobject1 creat kref is : %d\n",
           mykobject1->kref.refcount.refs.counter);

    // 添加mykobject 2 查看引用计数
    mykobject2 = kobject_create_and_add("mykobject2", mykobject1);
   printk("mykobject2 creat kref is : %d\n",
           mykobject2->kref.refcount.refs.counter);
   printk("mykobject1  kref is : %d\n",
           mykobject1->kref.refcount.refs.counter);

    // 添加mykobject 3 查看引用计数
    mykobject3 = kobject_create_and_add("mykobject3", NULL);
   printk("mykobject3 creat kref is : %d\n",
           mykobject3->kref.refcount.refs.counter);
   printk("mykobject1  kref is : %d\n",
           mykobject1->kref.refcount.refs.counter);
   printk("mykobject2  kref is : %d\n",
           mykobject2->kref.refcount.refs.counter);

           return 0;
}

// 模块退出函数
static void myref_exit(void)
{
   printk("mykobject1  kref is : %d\n",
           mykobject1->kref.refcount.refs.counter);
   printk("mykobject2  kref is : %d\n",
           mykobject2->kref.refcount.refs.counter);
   printk("mykobject3  kref is : %d\n",
           mykobject3->kref.refcount.refs.counter);

        printk("delete mykobject1 \n");
    kobject_put(mykobject1);
   printk("mykobject1  kref is : %d\n",
           mykobject1->kref.refcount.refs.counter);
   printk("mykobject2  kref is : %d\n",
           mykobject2->kref.refcount.refs.counter);
   printk("mykobject3  kref is : %d\n",
           mykobject3->kref.refcount.refs.counter);

        printk("delete mykobject2 \n");
    kobject_put(mykobject2);
   printk("mykobject1  kref is : %d\n",
           mykobject1->kref.refcount.refs.counter);
   printk("mykobject2  kref is : %d\n",
           mykobject2->kref.refcount.refs.counter);
   printk("mykobject3  kref is : %d\n",
           mykobject3->kref.refcount.refs.counter);

        printk("delete mykobject3 \n");
    kobject_put(mykobject3);
   printk("mykobject1  kref is : %d\n",
           mykobject1->kref.refcount.refs.counter);
   printk("mykobject2  kref is : %d\n",
           mykobject2->kref.refcount.refs.counter);
   printk("mykobject3  kref is : %d\n",
           mykobject3->kref.refcount.refs.counter);
}

module_init(myref_init);
module_exit(myref_exit);
MODULE_LICENSE("GPL");